#!/bin/bash

cd $(dirname "${BASH_SOURCE[0]}")
echo "Current directory: $PWD"

if [ -z $RUNNER ]; then
    # docker or podman
    RUNNER="docker"
fi

echo "RUNNER: ${RUNNER}"

GIT_ROOT=$(git rev-parse --show-toplevel)
VENV_DIR="${GIT_ROOT}/.venv"
VERSION=$(yq -r .Version ${GIT_ROOT}/configuration/build_config.yaml)
CONTAINER_NAME=$(yq -r '.["Base-Name"]' ${GIT_ROOT}/configuration/build_config.yaml)

if [[ ! -d $VENV_DIR ]]; then
    echo "Preparing venv for the tests..."
    pushd .
    cd $GIT_ROOT
    python3 -m venv .venv
    popd
fi

source ${VENV_DIR}/bin/activate
pip install -r ${GIT_ROOT}/requirements.txt

echo "Cloning the example images..."

git clone https://github.com/Elektrobit/ebcl_template.git

echo "Running the image build tests for dev container ${VERSION}..."

export IMAGES="$PWD/ebcl_template/images"
export WORKSPACE="$PWD/ebcl_template"
export RESULTS=$PWD

echo "Running the container..."

${GIT_ROOT}/usage/run_background

sleep 5

$RUNNER ps | grep ${CONTAINER_NAME}

echo "Executing the tests..."

${RUNNER} exec ${CONTAINER_NAME} bash -c 'cd /workspace/robot_tests; echo "PWD: $PWD"; robot images.robot'

echo "Copying the test result..."

${RUNNER} exec ${CONTAINER_NAME} bash -c 'cp /workspace/robot_tests/*.html /build/results/'
${RUNNER} exec ${CONTAINER_NAME} bash -c 'cp /workspace/robot_tests/output.xml /build/results/'

echo "Stopping the container..."

${GIT_ROOT}/usage/stop_container

echo "Deleting the template..."

sudo rm -rf ebcl_template
